//
//  ESSCommitInventoryVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/24.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ESSCommitInventoryVC.h"
#import "CargoChooseCell.h"
#import "DoubleLabCell.h"
#import "NWESSRequest.h"
#import "ESSListModel.h"

#define kDataProductAttributeId  @"productAttributeId"

#define kDataNumber  @"number"

@interface ESSCommitInventoryVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *dataArr;

@property (nonatomic,strong) ESSListModel *listModel;

@property (nonatomic,assign) NSInteger week;

@property (nonatomic,strong) NSMutableArray*paraDataArr;    //上传参数字典中 data对应的value

@property (nonatomic,strong) NSMutableArray*selectDataArr;  //选中的商品数据源

@end

@implementation ESSCommitInventoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self paraDataArr];
    [self selectDataArr];
    
    NWESSRequest *request = [[NWESSRequest alloc] init];
    [request startRequestGetInventoryWithUserId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        _listModel = [[ESSListModel alloc] initWithDictionary:result error:nil];
        
        NSMutableArray *arr = [ESSInventoryModel arrayOfModelsFromDictionaries:_listModel.inventoryProductList];
        _dataArr = [NSMutableArray arrayWithArray:arr];
        [self setUpUI];
    }];
}

- (NSMutableArray *)paraDataArr
{
    if (!_paraDataArr) {
        _paraDataArr = [NSMutableArray array];
    }
    return _paraDataArr;
}

- (NSMutableArray *)selectDataArr
{
    if (!_selectDataArr) {
        _selectDataArr = [NSMutableArray array];
    }
    return _selectDataArr;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"提交库存";
    
    
    //创建列表
    TPKeyboardAvoidingTableView *tabView = [[TPKeyboardAvoidingTableView
                             alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    tabView.backgroundColor = KwBgColor;
    tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tabView.estimatedRowHeight = 40.0;
    tabView.rowHeight = UITableViewAutomaticDimension;
    tabView.delegate = self;
    tabView.dataSource = self;
    [self.view addSubview:tabView];
    [tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];
    
    //创建底部按钮
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(startPlaceAnOrder) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius= 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

//开始下单
- (void)startPlaceAnOrder
{
    for (ESSInventoryModel *model in _dataArr)
    {
        if (model.totalBox)
        {
            [_selectDataArr addObject:model];
        }
    }
    for (int i = 0; i<_selectDataArr.count; i++)
    {
        ESSInventoryModel *model = _selectDataArr[i];
        [_paraDataArr addObject:@{kDataProductAttributeId:model.productAttributeId,kDataNumber:model.totalBox}];
    }
    
    NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
    NWESSRequest *request = [[NWESSRequest alloc] init];
    [request startRequestUpdateInventoryWithUserId:[Singleton shareInstance].userId data:dataStr];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            [SVProgressHUD showSuccessWithStatus:@"更新库存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}
#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else
    {
        return _dataArr.count;
    }
}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *headView = [UIView new];
//    UILabel *lab = [UILabel new];
//    lab.text = @"营养多";
//    lab.textAlignment = NSTextAlignmentLeft;
//    lab.font = KwFont(14);
//    lab.textColor = KwBgColor;
//    [headView addSubview:lab];
//    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(@20);
//        make.top.equalTo(@10);
//        make.bottom.equalTo(@-10);
//    }];
//    return headView;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *doubleCell_id = @"DoubleLabCell";
    static NSString *cargoChooseCell_id = @"CargoChooseCell";
    if (indexPath.section == 0)
    {
        DoubleLabCell *cell = [tableView dequeueReusableCellWithIdentifier:doubleCell_id];
        if (!cell)
        {
            cell = [[DoubleLabCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:doubleCell_id];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        if (indexPath.row == 0)
//        {
            cell.constStr = @"日期";
            
            NSDate * senddate=[NSDate date];
            NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"HH:mm"];
//            NSString * locationString=[dateformatter stringFromDate:senddate];
            
            NSCalendar * cal=[NSCalendar currentCalendar];
            NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
            NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
            NSInteger year=[conponent year];
            NSInteger month=[conponent month];
            NSInteger day=[conponent day];
            float a = day/7;
            if (a<=1)
            {
                _week = 1;
            }
            else
            {
                _week = ceil(a+1);
            }
            
            NSString * nsDateString= [NSString stringWithFormat:@"%d-%d",year,month];
            
            cell.paraStr = nsDateString;
            
//        }
//        else
//        {
//            cell.constStr = @"第几周";
//            cell.paraStr = [NSString stringWithFormat:@"第%d周",_week];
//        }
        return cell;
    }
    else
    {
        
        CargoChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:cargoChooseCell_id];
        
        if (!cell)
        {
            cell = [[CargoChooseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cargoChooseCell_id];
        }
        cell.isUpdateInventory = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = _dataArr[indexPath.row];
        
        
        
        __weak CargoChooseCell *weakCell = cell;
        cell.numAddBlock =^(NSString *count){
            
            ESSInventoryModel *model = [_dataArr objectAtIndex:indexPath.row];
            
            weakCell.oNumberParaLab.text = count;
            model.totalBox = count;
            [_dataArr replaceObjectAtIndex:indexPath.row withObject:model];
        };
        
        cell.numCutBlock =^(NSString *count){
            
            ESSInventoryModel *model = [_dataArr objectAtIndex:indexPath.row];
            
            weakCell.oNumberParaLab.text = count;
            
            model.totalBox = count;
            [_dataArr replaceObjectAtIndex:indexPath.row withObject:model];
            
        };

        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}








/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
